<?php

namespace addons\rexam\controller;

use think\addons\Controller;
use think\Session;

class Base extends Controller
{
    protected $config;
    protected $rexam_user;
    protected $model = null;
    
    public function _initialize()
    {
        parent::_initialize();

        $this->config = get_addon_config('rexam');
        $this->assign('config', $this->config);

        if(!$this->auth->isLogin()){
            if($this->request->action() !== 'login' || $this->request->controller() !== 'user') {
                $url = addon_url('rexam/user/login');
                $this->redirect($url);
            }
        }else{
            $user_model = new \app\admin\model\rexam\User;
            $where = array();
            $where['user_id']=$this->auth->id;
            $this->rexam_user = $user_model
                ->with(['sysuser'])
                ->where($where)
                ->find();
            if(empty($this->rexam_user)){
                if($this->request->action() !== 'login' || $this->request->controller() !== 'user') {
                    $url = addon_url('rexam/user/login');
                    $this->redirect($url);
                }
            }
        }

        //用户尚未加入群组
        if(empty($this->rexam_user['rexam_group_id']) || empty($this->rexam_user['name'])){
            if($this->request->controller() !== 'group' &&  $this->request->controller() !== 'user') {
                $url = addon_url('rexam/group/index');
                $this->redirect($url);
            }
        }
        $this->assign("rexam_user", $this->rexam_user);
    }

    protected function ajax_success($msg = '', $data = null, $code = 1){
        $result = [
            'code'=>$code,
            'msg'=>$msg,
            'data'=>$data
        ];
        return json($result);
    }

    protected function ajax_failure($msg = '', $data = null, $code = 0){
        $result = [
            'code'=>$code,
            'msg'=>$msg,
            'data'=>$data
        ];
        return json($result);
    }
}